//============================================================================
// Name        : GWSocketClient.cpp
// Author      : Ge LIang
// Version     :
// Copyright   : @2016 GeLiang
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>
using namespace std;

#include "common.h"
#include "GWSocketHandler.h"
#include <stdlib.h>
#include <string.h>
#include "GWSocketClient.h"

GWSocketClient::GWSocketClient(SocketHandler *pSocketHandler, const char* host,
		int port, int recvTimeout) :
		SocketClient(pSocketHandler, host, port, recvTimeout) {

}
GWSocketClient::~GWSocketClient() {

}

void GWSocketClient::login(int userID, const char* token, void* client) {

	GWLogin req;
	int lenFieldHeader = sizeof(GWLogin);
	memset(&req, 0, lenFieldHeader);
	req.header.cmd = 2501;
	req.header.size = lenFieldHeader;
	req.userid = userID;
	memset(req.token, 0, 32);
	memcpy(req.token, token, strlen(token));
	((SocketClient*) client)->send((char*) (&req), req.header.size);
}
void GWSocketClient::heartbeat() {
	GWNullMsg req;
	int lenHeader = sizeof(GWHeader);
	memset(&req, 0, lenHeader);
	req.header.cmd = 2502;
	req.header.size = lenHeader;
	send((char*) (&req), req.header.size);
	LOGI("GWSocketClient::heartbeat ");
}
int GWSocketClient::sendMsgToAll(char* buf, int size, void* client) {
	if (buf == NULL) {
		return 0;
		LOGW("null Buffer will not be send");
	};
	int packetSize = sizeof(GWMsg) + size;
	GWMsg* req = (GWMsg*) malloc(packetSize);
	if (req == NULL) {
		return 0;
		LOGE("xx OOM xx");
	};
	memset(req, 0, packetSize);
	req->header.cmd = 112;
	req->header.size = packetSize;
	memcpy(req + 1, buf, size);
//	LOGI("send msg %d:%s", req->header.cmd, req + 1);
	((SocketClient*) client)->send((char*) (req), req->header.size);
	free(req);
	return packetSize;
}
int GWSocketClient::handleGWPacket(Packet* packet) {
	GWHeader* header = (GWHeader*) packet->data;
	switch (header->cmd) {
	case 2508:
		LOGI("login success");
		break;
	case 110:
		if (header->size - sizeof(GWHeader) < 1024) {
			char buffer[1024];
			memset(buffer, 0, 1024);
			memcpy(buffer, header + 1, header->size - sizeof(GWHeader));
			LOGI("xxxxxxxxxxxxxxxxxxxxxxxxx");
			LOGI("RECV a message :%s", buffer);
			LOGI("xxxxxxxxxxxxxxxxxxxxxxxxx");
		} else {
			LOGW("RECV a message ,but size>1000");
		}
		break;
	default:
		break;
	};
	return packet->size;
}

